package com.ruoyi.system.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.SysKeystore;
import com.ruoyi.system.mapper.SysKeystoreMapper;
import com.ruoyi.system.service.ISysKeystoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @author renzhihao
 * @date 2023/10/12 15:58
 */
@Service
public class SysKeystoreServiceImpl implements ISysKeystoreService {
    private static final Logger log = LoggerFactory.getLogger(SysKeystoreServiceImpl.class);

    @Autowired
    private SysKeystoreMapper keystoreMapper;

    @Autowired
    private ServerConfig serverConfig;

    @Override
    public List<SysKeystore> selectKeystoreList(SysKeystore keystore) {
        return keystoreMapper.selectKeystoreList(keystore);
    }

    @Override
    public int insertKeystore(SysKeystore keystore) {
        keystore.setCreateBy(ShiroUtils.getLoginName());
        String keystoreName = keystore.getKeystoreName();
        String filePath = RuoYiConfig.getUploadPath();
        String fileName = FileUploadUtils.extractFilename(new File(keystoreName));
        String absPath = FileUploadUtils.getAbsoluteFile(filePath, fileName).getAbsolutePath();

        String alg = StringUtils.isBlank(keystore.getAlg()) ? "RSA" : keystore.getAlg();
        String cn = StringUtils.isBlank(keystore.getCn()) ? "unknown" : keystore.getCn();
        String ou = StringUtils.isBlank(keystore.getOu()) ? "unknown" : keystore.getOu();
        String o = StringUtils.isBlank(keystore.getO()) ? "unknown" : keystore.getO();
        String l = StringUtils.isBlank(keystore.getL()) ? "unknown" : keystore.getL();
        String st = StringUtils.isBlank(keystore.getSt()) ? "unknown" : keystore.getSt();
        String c = StringUtils.isBlank(keystore.getC()) ? "unknown" : keystore.getC();

        String name = String.format("cn=%s,ou=%s,o=%s,l=%s,st=%s,c=%s", cn, ou, o, l, st, c);
        String command = String.format("keytool -genkeypair -keyalg %s -dname \"%s\" -alias %s -keystore %s -keypass %s -storepass %s",
                alg, name, keystore.getAlias(), absPath, keystore.getPrivateKeyPass(), keystore.getKeystorePass());

        try {
            Process exec = Runtime.getRuntime().exec(command);
            int exitCode = exec.waitFor();

            if (exitCode == 0) {
                File file = new File(absPath);
                if (!FileUtils.exist(file)) {
                    log.warn("文件{}不存在", absPath);
                    return -1;
                }
            } else {
                log.warn("命令执行失败,错误码：{}", exitCode);
                return -1;
            }

            String newFileName = FileUploadUtils.getPathFileNameNoResource(filePath, fileName);

            keystore.setFileName(newFileName);
            keystore.setFileUrl(serverConfig.getUrl() + newFileName);
        } catch (Exception e) {
            log.error("生成文件错误：", e);
            return -1;
        }

        return keystoreMapper.insertKeystore(keystore);
    }

    @Override
    public SysKeystore selectKeystoreById(Long keystoreId) {
        return keystoreMapper.selectById(keystoreId);
    }

    @Override
    public int deleteKeystoreByIds(Long[] ids) {
        List<SysKeystore> keystores = keystoreMapper.selectByIds(ids);
        int count = keystoreMapper.deleteKeystoreByIds(ids);
        if (count == ids.length) {
            for (SysKeystore keystore : keystores) {
                String filePath = RuoYiConfig.getUploadPath();
                String absPath = FileUploadUtils.getAbsoluteFile(filePath, keystore.getFileName()).getAbsolutePath();
                FileUtils.deleteFile(absPath);
            }
        }
        return count;
    }

    @Override
    public List<SysKeystore> selectByIds(Long[] keystoreId) {
        return keystoreMapper.selectByIds(keystoreId);
    }

    @Override
    public boolean checkKeystoreNameUnique(SysKeystore keystore) {
        Long keystoreId = StringUtils.isNull(keystore.getKeystoreId()) ? -1L : keystore.getKeystoreId();
        SysKeystore info = keystoreMapper.checkKeystoreNameUnique(keystore.getKeystoreName());
        if (StringUtils.isNotNull(info) && info.getKeystoreId().longValue() != keystoreId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public List<SysKeystore> selectKeystoreAll() {
        return keystoreMapper.selectKeystoreAll();
    }

    @Override
    public int updateKeystore(SysKeystore keystore) {
        keystore.setUpdateBy(ShiroUtils.getLoginName());
        return keystoreMapper.updateKeystore(keystore);
    }
}
